<template>
	<picker mode="multiSelector" :range="currentRegionList" range-key="label" :value="tempRegionValue"
		@change="regionChange" @columnchange="regionColumnchange" @cancel="regionCancel">
		<slot :region="region"></slot>
	</picker>
</template>
<script lang="ts">
	import { defineComponent } from "vue"
	export default defineComponent({
		// #ifdef MP-WEIXIN
		options: {
			virtualHost: true,
			// styleIsolation: 'shared'
		},
		// #endif
	})
</script>
<script lang="ts" setup>
	import type { AnyObj } from '@/types/global';
	import { getRegionTree } from '@/apis/common';
	import { onMounted, ref, computed, defineEmits } from 'vue';
	type Region = { label : string; children ?: { label : string; }[] };

	const emit = defineEmits<{ confirm : [region: string]; 'update:modelValue' : [region: string] }>();

	const regionList = ref<Region[]>([{ label: '不限', children: [{ label: '不限' }] }]);
	const regionValue = ref<[number, number]>([0, 0]);
	const tempRegionValue = ref<[number, number]>([0, 0]);
	const currentRegionList = computed(() => {
		const [firstIndex] = tempRegionValue.value;
		return [regionList.value, regionList.value[firstIndex].children]
	});
	const region = computed(() => {
		const [firstIndex, lastIndex] = regionValue.value;
		const find = regionList.value[firstIndex];
		const firstLabel = find.label ?? '不限';
		if (firstLabel === '不限') {
			return { text: firstLabel, value: '' };
		}
		const lastLabel = find?.children?.[lastIndex]?.label ?? '不限';
		if (lastLabel === '不限') {
			return { text: firstLabel, value: firstLabel };
		}
		return { text: `${firstLabel}-${lastLabel}`, value: lastLabel }
	});
	function regionCancel() {
		tempRegionValue.value = [...regionValue.value];
	}
	function regionChange(event : { detail : { value : [number, number]; } }) {
		regionValue.value = event.detail.value;
		emit('update:modelValue', region.value.value)
		emit('confirm', region.value.value)
	}
	function regionColumnchange(event : { detail : { column : number; value : number } }) {
		if (event.detail.column === 0) {
			tempRegionValue.value = [event.detail.value, 0]
			return;
		}
		tempRegionValue.value[event.detail.column] = event.detail.value;
	}

	onMounted(() => {
		console.log('mountedmountedmounted');
		getRegionTree().then((res) => {
			const data = (res.data ?? []) as Region[];
			for (const item of data) {
				item.children = [{ label: '不限' }, ...(item.children ?? [])]
			}
			regionList.value = [
				{ label: '不限', children: [{ label: '不限' }] },
				...data
			];
		});
	});
</script>

<style>
</style>